﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Net;
using SPArtistic.ExchangeServiceBinding;

namespace SPArtistic.CalendarItemSync
{
    public class ItemAddedEventHandler : SPItemEventReceiver
    {
        public override void ItemAdded (SPItemEventProperties properties)
        {
            //run the default event handlers on the item
            base.ItemAdded(properties);
                       
            try
            {
                ////impersonate an administrator who can change permissions on list items in the list
                //ImpersonationUtility imp = ImpersonationUtility.ImpersonateAdmin();
                ////open the spweb object to get the token for the user
                //using (SPWeb webOrigUser = properties.OpenWeb())
                //{
                //    //get the token for the impersonation user (this will get the user that the ImpersonationUtility is using)
                //    SPUserToken token = webOrigUser.AllUsers[WindowsIdentity.GetCurrent().Name].UserToken;
                //    //reopen the spweb object with the new token - full impersonation!
                    using (SPSite site = new SPSite(properties.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
                        {

                            //call the function that changes the permissions on the list item. 
                            //Do not use properties.ListItem since that will break impersonation!
                            SendmeetingRequest(web.Lists[properties.ListId].GetItemById(properties.ListItemId));
                        }
                    }
                

            }
            catch (Exception ex)
            {
             
            }
        }
        private void SendmeetingRequest(SPListItem item)
        {
            SPWeb myweb1 = item.Web;
            // Identify the service binding and the user.
            ExchangeServiceBinding.ExchangeServiceBinding esb = new ExchangeServiceBinding.ExchangeServiceBinding();
            
            esb.Credentials = new NetworkCredential("username", "password", "domain");
            //esb.Credentials = CredentialCache.DefaultCredentials;
            // esb.Url = @"https://<FQDN>/EWS/Exchange.asmx";
            esb.Url = @"https://mail.exchangeserver.com/ews/Exchange.asmx";


            // Create the appointment.
            CalendarItemType appointment = new CalendarItemType();

            // Add item properties to the appointment.
            appointment.Body = new BodyType();
            appointment.Body.BodyType1 = BodyTypeType.Text;
            appointment.Body.Value = "Agenda Items....";
            appointment.Categories = new string[] { "Category1", "Category2" };
            appointment.Importance = ImportanceChoicesType.High;
            appointment.ImportanceSpecified = true;
            appointment.ItemClass = "IPM.Appointment";
            appointment.Subject = "Advance Design Presentation";



            // Add calendar properties to the appointment.
            appointment.Start = System.DateTime.Parse("2012-07-30T14:00:00Z");
            appointment.StartSpecified = true;
            appointment.End = System.DateTime.Parse("2012-07-30T15:00:00Z");
            appointment.EndSpecified = true;
            appointment.Location = "Room1";
            appointment.ReminderMinutesBeforeStart = "15 minutes";
            appointment.RequiredAttendees = new AttendeeType[1];
            appointment.RequiredAttendees[0] = new AttendeeType();
            appointment.RequiredAttendees[0].Mailbox = new EmailAddressType();
            appointment.RequiredAttendees[0].Mailbox.EmailAddress = "test.@test.com";


            // Identify the destination folder that will contain the appointment.
            DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
            folder.Id = DistinguishedFolderIdNameType.calendar;

            // Create the array of items that will contain the appointment.
            NonEmptyArrayOfAllItemsType arrayOfItems = new NonEmptyArrayOfAllItemsType();
            arrayOfItems.Items = new ItemType[1];

            // Add the appointment to the array of items.
            arrayOfItems.Items[0] = appointment;

            // Create the CreateItem request.
            CreateItemType createItemRequest = new CreateItemType();

            // The SendMeetingInvitations attribute is required for calendar items.
            createItemRequest.SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy;
            createItemRequest.SendMeetingInvitationsSpecified = true;

            // Add the destination folder to the CreateItem request.
            createItemRequest.SavedItemFolderId = new TargetFolderIdType();
            createItemRequest.SavedItemFolderId.Item = folder;

            // Add the items to the CreateItem request.
            createItemRequest.Items = arrayOfItems;


            // Send the request and get the response.
            CreateItemResponseType createItemResponse = esb.CreateItem(createItemRequest);
           

        }
        

    }
}
